const fish = document.getElementById('fish')
const count = document.querySelector('#count')
const autoClick = document.querySelector('#autoClick')
const animation = document.querySelector('.animation')

let num = 0
let controller = false
let timer = null

+function (){
  function init(){
    num = localStorage.getItem('count') || 0
    count.innerText = num
  }

  function changeView(){
    num ++
    count.innerText = num
    audioObj.play()
    localStorage.setItem('count',num)
    fish.style.transform = 'scale(1.1)'
    animation.classList.remove('animation-class')
    animation.classList.add('animation-class')
    setTimeout(()=>{
      fish.style.transform = 'scale(1)'
      audioObj.load()
    },150)
    setTimeout(()=>{
      animation.classList.remove('animation-class')
    },300)
  }

  const audioObj = new Audio('https://s1.aigei.com/src/aud/mp3/d0/d0ef1a10faae4630aa02d91338c30e6f.mp3?e=1687192560&token=P7S2Xpzfz11vAkASLTkfHN7Fw-oOZBecqeJaxypL:CzQFVswI0KhG2H0z15qHQEeedZE=')
  audioObj.playbackRate = 1.5
  const events = {
    autoClickEvent: ()=>{
      if(controller) {
        clearInterval(timer)
        autoClick.classList.remove('press')
        controller = false
      }else{
        timer = setInterval(()=>{
          changeView()
        },500)
        autoClick.classList.add('press')
        controller = true
      }
    },
    keydownEvent:(e)=>{
      if(e.keyCode === 32){
      console.log(e.keyCode)
      controller = true
      events.autoClickEvent()
      changeView()
      }
      
    }
  }


  function addEvent(){
    fish.addEventListener('click',()=>{
      controller = true
      events.autoClickEvent()
      changeView()
    },false)
    document.addEventListener('keydown',events.keydownEvent,false)
    autoClick.addEventListener('click',events.autoClickEvent,false)
  }
  
  init()
  addEvent()
}()